<template>
	<div class="lyl-list">
		<!-- 线 -->
		<template v-for="(item, index) in state.left" :key="index">
			  <div class="lyl-line" :style="styleLine(index)"></div>
		</template>
		<div class="left">
		  <div v-for="(item, index) in state.left" :class="[{'active': state.leftTargetInfo.index === index}, `lyl-left-${index}`]" @click="handleSelect($event, index, 'left')">
			  <text>{{ item }}</text>
			</div>
		  <!-- <div><text id="start">这是一个</text></div> -->
		</div>
		<div class="right">
		  <div v-for="(item, index) in state.right" :class="[{'active': state.rightTargetInfo.index === index}, `lyl-right-${index}`]" @click="handleSelect($event, index, 'right')">
			  <text>{{ item }}</text>
			</div>
		  <!-- <div><text id="end">这是一个</text></div> -->
		</div>
	</div> 
</template>

<script setup>
import { ref, reactive, getCurrentInstance, computed, onMounted } from "vue"
import { shuffleArray } from "@/utils"
import { useTopic } from "../hook.js"
import Props from "../props.js"
const props = defineProps(Props)
const emit = defineEmits(['answer'])
const instance = getCurrentInstance()
const answer = ref({
	words: [],
	order: {}
})
const state = reactive({
	left: [],
	right: [],
	// 左则目标信息
	leftTargetInfo: {},
	// 右则目标信息
	rightTargetInfo: {},
	styleItem: [],
})
const styleLine = computed(() => {
	return (index) => {
		return state.styleItem?.[index] || ''
	}
})
const handleSelect = (e, index, dir) => {
	if(!props.isStart) { return }
	const currentTarget = e.currentTarget
	// 左则
	if(dir === 'left') { 
		state.leftTargetInfo.flag = true
		state.leftTargetInfo.index = index
		state.leftTargetInfo.target = e.currentTarget
	}
	// 右则
	if(dir === 'right') { 
		state.rightTargetInfo.flag = true
		state.rightTargetInfo.index = index
		state.rightTargetInfo.target = e.currentTarget
	}
	const className = dir === 'left' ? `.lyl-left-${index}` :`.lyl-right-${index}`
	wx.createSelectorQuery().in(instance).select(className).boundingClientRect(function(res){
		if(dir === 'left') { state.leftTargetInfo.info = res }
		if(dir === 'right') { state.rightTargetInfo.info = res }
		// 两者存在
		if(state.leftTargetInfo.flag && state.rightTargetInfo.flag) {
			
			emit('answer', answer.value)
			createLine().then((res) => {
				// 记录连接顺序
				answer.value.order[res.index] = [res.x1, res.y1, res.x2, res.y2]
			})
		}
	}).exec()
}
// 生成连接线
const createLine = (params = [], i) => {
	return new Promise((resolve, reject) => {
		const left = state.leftTargetInfo
		const right = state.rightTargetInfo
		const index = i !== undefined ? i : state.leftTargetInfo.index
		// 开始点、结束点
		const x1 = params?.[0] || left.info.width + 5
		const y1 = params?.[1] || left.target.offsetTop + left.info.height / 2
		const x2 = params?.[2] || right.target.offsetLeft
		const y2 = params?.[3] || right.target.offsetTop + right.info.height / 2
		// 角度计算
		const angle = calculateRotationAngle(x1, y1, x2, y2)
		// 线段长度
		const width = calculateDistance(x1, y1, x2, y2) + 10
		// 线段生成
		const style = { left:x1 + 'px', top: y1 + 'px', width: `${width}px`, transform: `rotate(${angle}deg)`}
		state.styleItem[index] = style
		// 重置
		state.leftTargetInfo = {}
		state.rightTargetInfo = {}
		resolve({x1, y1, x2, y2, index})
	})
	
}
function calculateDistance(x1, y1, x2, y2) {
    const deltaX = x2 - x1;
    const deltaY = y2 - y1;
    const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
    return distance - 16;
}
function calculateRotationAngle(x1, y1, x2, y2) {
    // 计算 delta x 和 delta y
    let deltaX = x2 - x1;
    let deltaY = y2 - y1;
    // 计算角度（以弧度为单位）
    let angleInRadians = Math.atan2(deltaY, deltaX);
    // 将角度转换为度（可选）
    let angleInDegrees = angleInRadians * (180 / Math.PI);
    return angleInDegrees;
}
// function setWidth(value) {
//   const baseWidth = 375; // 基准宽度
//   const leftRpx = (value / baseWidth) * 750; // 转换为rpx
//   return leftRpx
// }

// function setHeight(value) {
//   const baseWidth = 375; // 基准宽度
//   const topRpx = (value / baseWidth) * 750; // 转换为rpx
//   return topRpx
// }
// 初始左右两侧文字，随机打乱位置
const init = () => {
	console.log('result', props.result)
	let left = []
	let right = []
	const list = props.data.data
	list.forEach((item, index) => {
		const split = item.split('|')
		left.push(split[0])
		right.push(split[1])
		// 显示结果
		if(!props.showInput && props.result.order[index]){ createLine(props.result.order[index], index) }
	})
	// left = shuffleArray(left)
	right = props.showInput ? shuffleArray(right) : props.result.words
	state.left = left
	state.right = right
	// 答案
	answer.value.words = right
}
onMounted(() => {
	init()
})

</script>

<style lang="scss" scoped>
@import "@/styles/var.scss";
.lyl-list {
	position: relative;
	margin: 0 auto;
	display: flex;
	align-items: flex-start;
	justify-content: space-between;
	font-size: 1.6rem;
	width: 27rem;
	.left, .right {
		display: flex;
		flex-direction: column;
		row-gap: 3rem;
		text { line-height: 1; }
		> div {
			position: relative;
			line-height: 1;
		}
		.active::before {
			content: "";
			position: absolute;
			width: 0.6rem;
			height: 0.6rem;
			border-radius: 2.5rem;
			background-color: #000;
			top: 50%;
			transform: translateY(-50%);
		}
	}
	.left {
		.active::before { left: 105%; }
	}
	.right {
		.active::before { right: 105%; }
	}
}
.lyl-line {
	position: absolute;
	width: 0;
	border: none;
	border-bottom: 1px solid #000;
	transform-origin: left;
}
</style>